package com.cheney.demo.io;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BackDatabaseUtils {
	/**
	 * 备份mysql数据库--yd
	 * 
	 * 备份数据库： mysqldump -hlocalhost -u root -p123 log > 备份文件.sql 恢复数据库： mysql -u
	 * root -p123 --default-character-set=utf8 log < 备份文件.sql
	 */
	public static void backMysqlTask(String folderPath) throws IOException {
		Runtime runtime = Runtime.getRuntime();
		// -u后面是用户名，-p是密码-p后面最好不要有空格，-family是数据库的名字
		Process process = runtime.exec("mysqldump -hlocalhost -u root -proot test");
		InputStream inputStream = process.getInputStream();// 得到输入流，写成.sql文件
		InputStreamReader reader = new InputStreamReader(inputStream);
		BufferedReader br = new BufferedReader(reader);
		String s = null;
		StringBuffer sb = new StringBuffer();
		while ((s = br.readLine()) != null) {
			sb.append(s + "\r\n");
		}
		s = sb.toString();
		System.out.println(s);

		Date now = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss");
		String sqlName = simpleDateFormat.format(now) + ".sql";
		File file = new File(folderPath +File.separator+ sqlName);

		file.getParentFile().mkdirs();
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		fileOutputStream.write(s.getBytes());
		fileOutputStream.close();
		br.close();
		reader.close();
		inputStream.close();

	}
}
